package com.baihan.angus.app.game.busshow.ui.user.edit;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.baihan.angus.app.game.basic.base.BaseActivity;
import com.baihan.angus.app.game.basic.utils.AppUtil;
import com.baihan.angus.app.game.basic.utils.ComUtil;
import com.baihan.angus.app.game.basic.utils.Tooast;
import com.baihan.angus.app.game.busshow.BR;
import com.baihan.angus.app.game.busshow.R;
import com.baihan.angus.app.game.busshow.databinding.ActivityEditUserBinding;
import com.baihan.angus.app.game.busshow.pop_dialog.SelectPicDialog;
import com.baihan.angus.app.game.common.arouter_path.ArouterAppPath;
import com.baihan.angus.app.game.common.bean.response.UploadResponse;
import com.baihan.angus.app.game.common.bean.response.Userinfo;
import com.baihan.angus.app.game.common.configs.UserConfig;
import com.baihan.angus.app.game.common.util.ImageLoader;
import com.baihan.angus.app.game.common.util.PhotoUtil;
import com.baihan.angus.app.game.common.util.imagepickerhelper.ImageOperateHelper;
import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lcw.library.imagepicker.ImagePicker;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 编辑资料
 */
@Route(path = ArouterAppPath.EDIT_USER_ACTIVITY)
public class EditUserActivity extends BaseActivity<ActivityEditUserBinding, EditUserVM> {

    public static final int PERMISSION_IMAGE = 0xb12;
    public static final int REQUEST_CODE_EDIT_USER = 0xb13;

    public final static String TAG_AVATAR = "tag_avatar";
    public final static String TAG_BG = "tag_bg";
    public String currentTag;

    private SelectPicDialog mSelectPicDialog;

    private Userinfo userinfo;
    private UploadResponse mUploadResponse;
    private int gender = 1;//0-女 1-男
    private String avatarUrl;
    private String bgUrl;

    private Map<String, Object> mModifyRequest = new HashMap<>();

    @Override
    protected int getContentLayout() {
        return R.layout.activity_edit_user;
    }

    @Override
    protected int getViewModelId() {
        return BR.editUserVM;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {

        userinfo = UserConfig.getUserConfig().getUser();

        initUserData(userinfo);

//        mVDBinding.ivBack.setOnClickListener(view -> finish());
//
//        mVDBinding.tvSave.setOnClickListener(view -> {
//            mModifyRequest.put("avatar", url);
//            mModifyRequest.put("gender", gender);
//            mModifyRequest.put("nickname", userinfo.getNickname());
//            mModifyRequest.put("bio", userinfo.getBio());
//            mViewModel.modifyUserInfo(mModifyRequest);
//        });

        mVDBinding.titleView.setLeftOnClickListener(view -> finish());

        mVDBinding.titleView.setRightOnClickListener(view -> {
            mModifyRequest.put("avatar", avatarUrl);
            mModifyRequest.put("gender", gender);
            mModifyRequest.put("nickname", userinfo.getNickname());
            mModifyRequest.put("bio", userinfo.getBio());
            mModifyRequest.put("background_image", bgUrl);
            mViewModel.modifyUserInfo(mModifyRequest);
        });

        mVDBinding.ivAvatar.setOnClickListener(view -> {
            uploadPic();
            currentTag = TAG_AVATAR;
        });

        mVDBinding.ivBg.setOnClickListener(view -> {
            uploadPic();
            currentTag = TAG_BG;
        });

        mVDBinding.rlNickName.setOnClickListener(view -> {
            ARouter.getInstance().build(ArouterAppPath.EDIT_NICK_NAME_ACTIVITY)
                    .withSerializable("userinfo", userinfo).navigation();
        });

        mVDBinding.rlIntro.setOnClickListener(view -> {
            ARouter.getInstance().build(ArouterAppPath.EDIT_INTRO_ACTIVITY)
                    .withSerializable("userinfo", userinfo).navigation();
        });

        mVDBinding.rlSex.setOnClickListener(view -> {
            new QMUIBottomSheet.BottomListSheetBuilder(this).addItem(getString(R.string.man)).addItem(getString(R.string.women))
                    .setAddCancelBtn(true).setCancelText(getString(R.string.cancel)).setGravityCenter(true)
                    .setOnSheetItemClickListener((dialog, itemView, position, tag) -> {
                        dialog.cancel();
                        if (position == 0) {
                            gender = 1;
                            mVDBinding.tvSex.setText(getString(R.string.man));
                        } else if (position == 1) {
                            gender = 0;
                            mVDBinding.tvSex.setText(getString(R.string.women));
                        }
                    }).build().show();
        });
    }

    public void initUserData(Userinfo userinfo) {
        ImageLoader.loadImage(this, mVDBinding.ivAvatar, userinfo.getAvatar(), R.mipmap.ic_test_bg, 0);
        ImageLoader.loadImage(this, mVDBinding.ivBg, userinfo.getBackground_image(), R.mipmap.ic_placeholder_pic, 0);
        mVDBinding.tvNickName.setText(userinfo.getNickname());
        mVDBinding.tvID.setText(userinfo.getUser_id());
        mVDBinding.tvBirthday.setText(userinfo.getBirthday());
        if (!TextUtils.isEmpty(userinfo.getBio())) {
            mVDBinding.tvUserIntro.setText(userinfo.getBio());
        }
        switch (userinfo.getRole_id()) {
            case 0:
                mVDBinding.tvUserType.setText("普通玩家");
                break;
            case 3:
                mVDBinding.tvUserType.setText("发行");
                break;
            case 4:
                mVDBinding.tvUserType.setText("店家");
                break;
            case 5:
                mVDBinding.tvUserType.setText("DM");
                break;
            case 6:
                mVDBinding.tvUserType.setText("编剧");
                break;
        }
        if (userinfo.getGender() == 0) {
            mVDBinding.tvSex.setText("女");
        } else if (userinfo.getGender() == 1) {
            mVDBinding.tvSex.setText("男");
        }
    }

    @Override
    protected void initObservers() {
        super.initObservers();

        mViewModel.mldUpload.observe(this, new Observer<UploadResponse>() {
            @Override
            public void onChanged(UploadResponse uploadResponse) {
                if (null != uploadResponse) {
                    mUploadResponse = uploadResponse;
                    if (currentTag.equals(TAG_AVATAR)) {
                        avatarUrl = uploadResponse.getData().getUrl();
                        userinfo.setAvatar(avatarUrl);
                        ImageLoader.loadImage(EditUserActivity.this, mVDBinding.ivAvatar, avatarUrl, R.mipmap.ic_test_bg, 0);
                    } else if (currentTag.equals(TAG_BG)) {
                        bgUrl = uploadResponse.getData().getUrl();
                        userinfo.setBackground_image(bgUrl);
                        ImageLoader.loadImage(EditUserActivity.this, mVDBinding.ivBg, bgUrl, R.mipmap.ic_test_bg, 0);
                    }
                    UserConfig.getUserConfig().saveUser(userinfo);
//                    mViewModel.modifyAvatar();
                }
            }
        });

        mViewModel.mldModifyResult.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    Tooast.normalInfo(getString(R.string.saveSuccess));
                    mViewModel.getUserInfo();
                }
            }
        });
    }

    private void uploadPic() {
        PermissionUtils.permission(PermissionConstants.CAMERA, PermissionConstants.STORAGE).callback(new PermissionUtils.FullCallback() {
            @Override
            public void onGranted(List<String> permissionsGranted) {
                showDialog();
            }

            @Override
            public void onDenied(List<String> permissionsDeniedForever, List<String> permissionsDenied) {
                ToastUtils.showShort(R.string.open_permission);
            }
        }).request();
    }

    private void showDialog() {
        if (null == mSelectPicDialog) {
            mSelectPicDialog = new SelectPicDialog(this, new SelectPicDialog.Callback() {
                @Override
                public void onTakePhoto() {
                    PhotoUtil.openCameraImage(EditUserActivity.this);
                    mSelectPicDialog.dismiss();
                }

                @Override
                public void onAlbum() {
                    startImageLib();
                    mSelectPicDialog.dismiss();
                }
            });
        }
        mSelectPicDialog.show();
    }

    private void startImageLib() {
        ImageOperateHelper.startImagePicker(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ImageOperateHelper.REQUEST_SELECT_IMAGES_CODE) {
            if (resultCode == RESULT_OK) {
                List<String> imagePaths = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);
                Luban.with(this).load(imagePaths.get(0))
                        .setTargetDir(AppUtil.getLubanPath())
                        .ignoreBy(100)
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                                showLoading("Compress");
                            }

                            @Override
                            public void onSuccess(File file) {
                                hideLoading("Compress");
                                mViewModel.uploadFile(file, currentTag);
                            }

                            @Override
                            public void onError(Throwable e) {
                                hideLoading("Compress");
                                Tooast.normalInfo(getString(R.string.compassPicFail));

                            }
                        }).launch();
            }
        } else if (requestCode == PhotoUtil.GET_IMAGE_BY_CAMERA) {
            if (resultCode == RESULT_OK) {
                File imageFile;
                imageFile = ComUtil.getUriBeforeKitKat(this, PhotoUtil.imageUriFromCamera);
                Luban.with(this).load(imageFile)
                        .setTargetDir(AppUtil.getLubanPath())
                        .ignoreBy(100)
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                                showLoading("Compress");
                            }

                            @Override
                            public void onSuccess(File file) {
                                hideLoading("Compress");
                                mViewModel.uploadFile(file, currentTag);
                            }

                            @Override
                            public void onError(Throwable e) {
                                hideLoading("Compress");
                                Tooast.normalInfo(getString(R.string.compassPicFail));

                            }
                        }).launch();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        userinfo = UserConfig.getUserConfig().getUser();
        initUserData(userinfo);
    }
}